package com.xb.cloud.gateway.utils;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: WebUtil
 * @Description:
 * @author william
 * @date 2011-2-24 下午05:56:33
 * 
 */
public class WebUtil {
	
	private final static Logger LOG = LoggerFactory.getLogger(WebUtil.class);
	
	/**
	 * 对url按照给定的字符集进行转义
	 * 
	 * @param url
	 *            原始url字符串
	 * @return
	 */
	public static String encodeUrl(final String url, final String charSet) {
		String retUrl = url; // 存储转义字符串
		try {
			retUrl = URLEncoder.encode(url, charSet);
		} catch (UnsupportedEncodingException e) {
			// 由函数使用字符集不存生而抛出的异常.可以避免
			LOG.error(e.getMessage(), e);
		}
		return retUrl;
	}

	/**
	 * 对url按照给定的字符集进行转义
	 * 
	 * @param url
	 *            原始url字符串
	 * @return
	 */
	public static String decodeUrl(final String url, final String charSet) {
		String retUrl = url; // 存储转义字符串
		/********************************/
		try {
			retUrl = URLDecoder.decode(url, charSet);
		} catch (UnsupportedEncodingException e) {
			// 由函数使用字符集不存生而抛出的异常.可以避免
			LOG.error(e.getMessage(), e);
		}
		return retUrl;
	}
	/**
	 * 获取用户的IP
	 * @Title: getClientIP   
	 * @Description: TODO 
	 * @param: @param request
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String getClientIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		String unknown = "unknown";
		if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isBlank(ip) || unknown.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (StringUtils.isBlank(ip)) {
			return "";
		}
		// 多个路由时，取第一个非unknown的ip
		final String[] arr = ip.split(",");
		for (final String str : arr) {
			if (!unknown.equalsIgnoreCase(str)) {
				ip = str;
				break;
			}
		}
		return ip;
	}
	
	public static String getLocalIp(){
		String ip = "";
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return ip;
	}
}
